package model;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BlogDao {
    public void insert(Blog blog) throws SQLException {
        Connection connection =null;
        PreparedStatement preparedStatement =null;
        connection = DBUtil.geConnection();
        String sql = "insert into blog values(null,?,?,now(),null)";
         preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
         preparedStatement.setString(1, blog.getTitle());
         preparedStatement.setString(2,blog.getContent());
         preparedStatement.setInt(3,blog.getUserId());
         preparedStatement.executeUpdate();
         DBUtil.close(connection,preparedStatement,null);
    }
        public List<Blog> getBlogs() throws SQLException {
        List<Blog> list= new ArrayList<Blog>();
        Connection connection =null;
        PreparedStatement statement = null;
        connection=DBUtil.geConnection();
        String sql = "select* from blog";
        statement= (PreparedStatement) connection.prepareStatement(sql);
      ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()){
           Blog blog = new Blog();
           blog.setBlogId(resultSet.getInt("blogId"));
           blog.setTitle(resultSet.getString("title"));
           String content= blog.getContent();
           if (content.length()>100){
               content=content.substring(0,100);
           }
           blog.setContent(content);
           blog.setPostTime(resultSet.getTimestamp("postTime"));
           blog.setUserId(resultSet.getInt("userId"));
           list.add(blog);
        }
        DBUtil.close(connection,statement,resultSet);
        return list;
        }

        public Blog getBlog(int blogId){
        return null;
        }
        public void delete(int blogId){
        return ;
        }
}
